<template>
    <div  class="app-container">
      <div class="filter-container">
        <el-button class="filter-item" type="primary" @click="handleCreate" v-if="isAdmin || isTeacher">
          添加考试
        </el-button>
      </div>
      <el-table
        :data="examList"
        border
        style="width: 100%"
       >
        <el-table-column
          prop="title"
          label="考试名称"
          width="180">
        </el-table-column>
        <el-table-column
           prop="examTime"
           label="考试时间"
           width="180">
        </el-table-column>
        <el-table-column
          prop="location"
          label="考试地点">
        </el-table-column>
        <el-table-column
          prop="teacher"
          label="监考老师">
        </el-table-column>
        <el-table-column
          v-if="isAdmin || isTeacher"
          label="操作"
          width="150">
          <template slot-scope="scope" >
            <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 添加/编辑对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
        <el-form :model="examForm" ref="examForm" :rules="rules" label-width="100px">
          <el-form-item label="考试名称" prop="title">
            <el-input v-model="examForm.title"></el-input>
          </el-form-item>
          <el-form-item label="考试时间" prop="time">
            <el-date-picker
                v-model="examForm.examTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="考试地点" prop="location">
            <el-input v-model="examForm.location"></el-input>
          </el-form-item>
          <el-form-item label="监考老师" prop="teacher">
            <el-input v-model="examForm.teacher"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import request from '@/utils/request'

  export default {
    name: 'ExamManagement',
    data() {
      return {
        examList: [],
        currentIndex: -1,
        dialogVisible: false,
        dialogTitle: '',
        examForm: {
          title: '',
          examTime: '',
          location: '',
          teacher: ''
        },
        rules: {
          title: [{ required: true, message: '请输入考试名称', trigger: 'blur' }],
          examTime: [{ required: true, message: '请选择考试时间', trigger: 'change' }],
          location: [{ required: true, message: '请输入考试地点', trigger: 'blur' }],
          teacher: [{ required: true, message: '请输入监考老师', trigger: 'blur' }]
        },
        // examList: [
        // {
        //     id: 1, // 添加唯一标识
        //     title: '2024年春季期末考试',
        //     time: '2024-09-18 11:01:13',
        //     location: 'XXXX',
        //     teacher: 'XXXX'
        //     },
        //     {
        //     id: 2, // 添加唯一标识
        //     title: '2024年春季期中考试',
        //     time: '2024-09-18 11:02:40',
        //     location: 'XXXX',
        //     teacher: 'XXXX'
        //     }
        // ],
      }
    },
    created() {
      this.fetchExamList()
    },
    computed: {
      isAdmin() {
        const userInfo = JSON.parse(localStorage.getItem('userInfo'))
        return userInfo && userInfo.studentId === 'admin' && userInfo.identity === '1'
      },
      isTeacher() {
        const userInfo = JSON.parse(localStorage.getItem('userInfo'))
        return userInfo && userInfo.identity == 1 && userInfo.studentId !== 'admin'
      }
    },
    methods: {
      async fetchExamList() {
        try {
          const res = await request({
            url: '/api/examSchedule/list',
            method: 'get'
          })
          if (res.code === '200') {
            this.examList = res.data
          }
        } catch (error) {
          console.error('获取考试安排失败:', error)
        }
      },
      handleCreate() {
        this.dialogTitle = '添加考试'
        this.examForm = {
          title: '',
          examTime: '',
          location: '',
          teacher: ''
        }
        this.dialogVisible = true
      },
      handleEdit(index, row) {
        this.dialogTitle = '编辑考试'
        this.currentIndex = index // 保存当前编辑项的索引
        this.examForm = {
            ...row,
            // time: row.time // 确保时间正确传递
        }
        this.dialogVisible = true
      },
      // handleDelete(index, row) {
      //   this.$confirm('确认删除该考试安排?', '提示', {
      //     confirmButtonText: '确定',
      //     cancelButtonText: '取消',
      //     type: 'warning'
      //   }).then(() => {
      //     this.examList.splice(index, 1)
      //     this.$message({
      //       type: 'success',
      //       message: '删除成功!'
      //     })
      //   }).catch(() => {
      //     this.$message({
      //       type: 'info',
      //       message: '已取消删除'
      //     })
      //   })
      // },
      async handleDelete(index, row) {
        try {
          await request({
            url: '/api/examSchedule/delete',
            method: 'post',
            params: { id: row.id }
          })
          this.examList.splice(index, 1)
          this.$message.success('删除成功!')
        } catch (error) {
          console.error('删除失败:', error)
        }
      },
      submitForm() {
        this.$refs.examForm.validate(async (valid) => {
          if (valid) {
            const formData = { ...this.examForm }
            try {
              if (this.dialogTitle === '添加考试') {
                await request({
                  url: '/api/examSchedule/create',
                  method: 'post',
                  data: formData
                })
                this.examList.push(formData)
              } else {
                await request({
                  url: '/api/examSchedule/update',
                  method: 'post',
                  data: formData
                })
                this.examList.splice(this.currentIndex, 1, formData)
              }
              this.dialogVisible = false
              this.$message.success(this.dialogTitle === '添加考试' ? '添加成功!' : '修改成功!')
            } catch (error) {
              console.error('提交失败:', error)
            }
          }
        })
      },
    //   submitForm() {
    //     this.$refs.examForm.validate((valid) => {
    //       if (valid) {
    //         const formData = {
    //           ...this.examForm,
    //           time: this.examForm.time // 确保时间格式正确
    //         }
    //         if (this.dialogTitle === '添加考试') {
    //           formData.id = Date.now() // 生成唯一ID
    //           this.examList.push(formData)
    //         } else {
    //           // 使用保存的索引进行更新
    //           this.examList.splice(this.currentIndex, 1, formData)
    //         }

    //         this.dialogVisible = false
    //         this.$message({
    //           type: 'success',
    //           message: this.dialogTitle === '添加考试' ? '添加成功!' : '修改成功!'
    //         })
    //       }
    //     })
    //  },
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .app-container {
    padding: 20px;
  }
  
  .filter-container {
    padding-bottom: 20px;
  }
  
  .el-dialog {
    .el-date-picker {
      width: 100%;
    }
  }
  </style>